<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------


namespace app\admin\controller;

use app\wap\controller\Kbxcoupon;
use app\wap\controller\Notify;
use \think\Db;
use \think\Cookie;
use app\admin\model\Order as Od;//管理员模型
use app\api\controller\Viator;
use app\api\controller\KbxOrder;
use app\api\controller\ExportExcel;
use think\Log;

class Order extends User
{

    public function _initialize()
    {
        header('Access-Control-Allow-Origin:*');

        Log::init([
            'type'  =>  'File',
            'path'  =>  APP_PATH.'logs/'
        ]);
    }

    public $statusArr = array(
        '1' => array(
            'orderStatus' => 'pending',
            'paymentStatus' => 'pending',
        ),
        '2' => array(
//            'orderStatus' => 'toBeStarting',
            'orderStatus' => 'pending',
            'paymentStatus' => 'paid',
        ),
        '3' => array(
            'orderStatus' => 'finished',
            'paymentStatus' => 'paid',
        ),
        '4' => array(
            'orderStatus' => 'reviewed',
            'paymentStatus' => 'paid',
        ),
        '5' => array(
            'orderStatus' => 'toBeStarting',
            'paymentStatus' => 'refunding',
        ),
        '6' => array(
            'orderStatus' => 'canceled',
            'paymentStatus' => 'refunding',
        ),
        '7' => array(
            'orderStatus' => 'expired',
            'paymentStatus' => 'pending',
        ),
        '8' => array(
            'orderStatus' => 'canceled',
            'paymentStatus' => 'refunded',
        ),
        '9' => array(
            'orderStatus' => 'toBeStarting',
            'paymentStatus' => 'rejected',
        ),
        '10' => array(
            'orderStatus' => 'unknown',
            'paymentStatus' => 'pending',
        )
    );

    /**
     * 订单列表
     * @return [type] [description]
     */
    public function index()
    {
        //实列化模型
        $post= request()->post();
        $temp_page=request()->param('page');
        $exportFlag=request()->param('exportFlag');//是否为导出
        if(isset($temp_page) || isset($exportFlag)){
            //条件从缓存取出
            $post=Cookie::get('postlist');
        }else{
            //把条件写入缓存
            Cookie::set('postlist',$post);
        }
        $recordsPerPage = 20;
        $page = $temp_page ? $temp_page :1;
        $url = request()->url();
        $urlArr = explode("?",$url);
        $url = $urlArr[0];

        //导出查询条件
        if($exportFlag==1){
            $recordsPerPage = 10000;
            $page = 1;
        }

        $KbxOrder = new KbxOrder();
        $data = $KbxOrder->kbx_order_by_page($page,$recordsPerPage,$post);//获取分页订单

        $orderList = array();
        if(!empty($data['returnedUserOrders'])){
            $totalNum = $data['totalRecords'];
            $totalPages = $data['totalPages'];

            //分页
            $paginate = $this->myPaginate($page,$totalPages,$totalNum,$url);
            foreach ($data['returnedUserOrders'] as $k=>$v) {
                if(isset($v['orderId']) && !isset($v['orderNo'])){
                    $v['orderNo'] = $v['orderId'];
                }

                //没有order_no就筛掉
                if(!isset($v['orderNo']) || $v['orderNo']==''){
                    continue;
                }
                $order = array();
                //判断状态
                $orderStatus = $v['status']['orderStatus'];
                $paymentStatus = $v['status']['paymentStatus'];
                $order['order_status']= 1;

                if($orderStatus=='pending' || $orderStatus=='carpool'){
                    if($paymentStatus=='pending'){
                        $order['order_status']= 1;//待付款
                        $kbx_url=config('kbx_url');
                        $order['url']=$kbx_url.'/2cstatic/#/affirm-order?orderId='.$v['id'];
                    }elseif($paymentStatus=='paid'){
                        $order['order_status']= 2;//已付款待使用
                    }elseif($paymentStatus=='refunding'){
                        $order['order_status']= 5;//退款申请中
                    }elseif($paymentStatus=='rejected'){
                        $order['order_status']= 9;//拒绝退款
                    }
                }elseif($orderStatus=='toBeStarting'){
                    if($paymentStatus=='paid'){
                        $order['order_status']= 2;//已付款待使用
                    }elseif($paymentStatus=='refunding'){
                        $order['order_status']= 5;//退款申请中
                    }elseif($paymentStatus=='rejected'){
                        $order['order_status']= 9;//拒绝退款
                    }
                }elseif($orderStatus=='reviewed'){//已评价
                    $order['order_status']= 4;
                }elseif($orderStatus=='finished'){//已使用待评价
                    $order['order_status']= 3;
                }elseif($orderStatus=='canceled'){//已取消
                    if($paymentStatus=='refunded'){
                        $order['order_status']= 8;//已退款
                    }else{
                        $order['order_status']= 6;
                    }
                }elseif($orderStatus=='expired'){//已过期
                    $order['order_status']= 7;
                }elseif($orderStatus=='unknown'){//下单失败
                    $order['order_status']= 10;
                }
                if(isset($v['booker']['memberId'])){
                    $member = db("member")->where("member_id",$v['booker']['memberId'])->field("member_nickname")->find();
                    $member_nickname = $member['member_nickname'];
                }else{
                    $member_nickname = $v['booker']['user']['profile']['name']??($v['booker']['user']['username']??'');
                }

                $order['source'] = 2;//mongo
                $order['order_no'] = isset($v['orderNo']) ? $v['orderNo'] : '';
                $order['order_id'] = isset($v['id']) ? $v['id'] : $v['_id'];
                $order['payType'] = isset($v['payType'])?$v['payType']:1;
                $order['typesource'] = $v['typeSource'];
                $order['goods'] = array('goods_name'=>$v['goods']['goodsName']);
                $order['member'] = array('member_nickname'=>$member_nickname);
                $order['fold_money'] = isset($v['payments']['foldMoney']) ? $v['payments']['foldMoney'] : $v['payments']['originalMoney'];
                $order['phone'] = isset($v['contact']['phone']) ? $v['contact']['phone'] : '';
                $order['isdelete'] = isset($v['isDelete']) ? $v['isDelete'] : 0;
                $order['refund_status'] = isset($v['refund']['refundStatus']) ? $v['refund']['refundStatus'] : 0;
                $order['speedstatus'] = isset($v['speedStatus']) ? $v['speedStatus'] : 0;
                $order['creattime'] = date('Y-m-d H:i:s',strtotime($v['createdAt']));
                $order['travelDate'] = isset($v['itinerary']['travelDate']) ? $v['itinerary']['travelDate'] : '';
                $creattime = strtotime($v['createdAt']);
                $orderList[$creattime] = $order;
            }
            if($page == $totalPages && $page>1){
                $end_time = strtotime($data['returnedUserOrders'][0]['createdAt']);
                $where['creattime'] = array("lt",$end_time);
            }else{
                $lastKey = count($data['returnedUserOrders'])-1;
                if($page>1){
                    $start_time = strtotime($data['returnedUserOrders'][$lastKey]['createdAt']);
                    $end_time = strtotime($data['returnedUserOrders'][0]['createdAt']);
                    $where['creattime'] = array(array("egt",$start_time),array("lt",$end_time));
                }else{
                    if($totalPages>1){
                        $start_time = strtotime($data['returnedUserOrders'][$lastKey]['createdAt']);
                        $where['creattime'] = array("egt",$start_time);
                    }
                }
            }

            //筛选
            if(!empty($post)){
                if(trim($post['order_no'])!==''){
                    $where['order_no'] = trim($post['order_no']);
                }
                if(trim($post['phone'])!==''){
                    $where['phone'] = trim($post['phone']);
                }
                if($post['order_status']!==''){
                    $where['order_status'] = $post['order_status'];
                }
                if($post['goods_source']!==''){
                    $where['typesource'] = $post['goods_source']==1 ? 'myself' : 'viator';
                }
                if($post['creattime']!==''){
                    $timrArr = explode("~",$post['creattime']);
                    $where['creattime'] = array(array("egt",strtotime($timrArr[0])),array("elt",strtotime($timrArr[1])));
                }
                if($post['travelDate']!==''){
                    $timrArr1 = explode("~",$post['travelDate']);
                    $where["travel_date"] = array('between',"STR_TO_DATE('".$timrArr1[0]."', '%Y-%m-%d'),STR_TO_DATE('".$timrArr1[1]."', '%Y-%m-%d')");
                }
            }

            $where['is_fake'] = 0;
            $my_order = Db::name("order")->where($where)->order('creattime','desc')->select();

            foreach ($my_order as $k=>$v) {
                $goods = db("goods")->where("goods_id",$v['goods_id'])->find();
                $member = db("member")->where("member_id",$v['member_id'])->find();
                $order = array();
                $order['source'] = 1;//mysql
                $order['order_no'] = $v['order_no'];
                $order['order_id'] = $v['order_id'];
                $order['payType'] = isset($v['pay_type'])?$v['pay_type']:1;
                $order['order_status'] = $v['order_status'];
                $order['typesource'] = $v['typesource'];
                $order['goods'] = array('goods_name'=>$goods['goods_name']);
                $order['member'] = array('member_nickname'=>$member['member_nickname']);
                $order['fold_money'] = $v['fold_money'];
                $order['phone'] = $v['phone'];
                $order['isdelete'] = $v['isdelete'];
                $order['refund_status'] = $v['refund_status'];
                $order['speedstatus'] = $v['speedstatus'];
                $order['creattime'] = date('Y-m-d H:i:s',$v['creattime']);
                $order['travelDate'] = $v['travel_date'];
                $order['comment_type'] =!empty($v['comment_type'])?$v['comment_type']:'0';
                $orderList[$v['creattime']] = $order;
            }
        }else{//订单系统无数据时
            //筛选
            $where = array();
            $where['is_fake'] = 0;
            if(!empty($post)){
                if(trim($post['order_no'])!==''){
                    $where['order_no'] = trim($post['order_no']);
                }
                if(trim($post['phone'])!==''){
                    $where['phone'] = trim($post['phone']);
                }
                if($post['order_status']!==''){
                    $where['order_status'] = $post['order_status'];
                }
                if($post['goods_source']!==''){
                    $where['typesource'] = $post['goods_source']==1 ? 'myself' : 'viator';
                }
                if($post['creattime']!==''){
                    $timrArr = explode("~",$post['creattime']);
                    $where['creattime'] = array(array("egt",strtotime($timrArr[0])),array("elt",strtotime($timrArr[1])));
                }
                if($post['travelDate']!==''){
                    $timrArr1 = explode("~",$post['travelDate']);
                    $where["travel_date"] = array('between',"STR_TO_DATE('".$timrArr1[0]."', '%Y-%m-%d'),STR_TO_DATE('".$timrArr1[1]."', '%Y-%m-%d')");
                }
            }

            $orderidArr = Db::name("order")->where($where)->field("order_id")->select();
            $startNum = ($page-1)*$recordsPerPage;
            $my_order = Db::name("order")->where($where)->order('creattime','desc')->limit($startNum,$recordsPerPage)->select();

            $totalNum = count($orderidArr);
            $totalPages = ceil($totalNum/$recordsPerPage);

            $paginate = $this->myPaginate($page,$totalPages,$totalNum,$url);

            foreach ($my_order as $k=>$v) {
                $goods = db("goods")->where("goods_id",$v['goods_id'])->find();
                $member = db("member")->where("member_id",$v['member_id'])->find();
                $order = array();
                $order['source'] = 1;//mysql
                $order['order_no'] = $v['order_no'];
                $order['order_id'] = $v['order_id'];
                $order['payType'] = isset($v['pay_type'])?$v['pay_type']:1;
                $order['order_status'] = $v['order_status'];
                $order['typesource'] = $v['typesource'];
                $order['goods'] = array('goods_name'=>$goods['goods_name']);
                $order['member'] = array('member_nickname'=>$member['member_nickname']);
                $order['fold_money'] = $v['fold_money'];
                $order['phone'] = $v['phone'];
                $order['isdelete'] = $v['isdelete'];
                $order['refund_status'] = $v['refund_status'];
                $order['speedstatus'] = $v['speedstatus'];
                $order['creattime'] = date('Y-m-d H:i:s',$v['creattime']);
                $order['travelDate'] = $v['travel_date'];
                $order['comment_type'] =$v['comment_type'];
                $orderList[$v['creattime']] = $order;
            }
        }

        krsort($orderList);
        $orderList = array_values($orderList);

        //导出方法
        if($exportFlag==1){
            $dataArr = array();
            $styleArr = array(
                1=>"待付款",
                2=>"已付款待使用",
                3=>"已使用待评价",
                4=>"已评价",
                5=>"退款中",
                6=>"已取消",
                7=>"已过期",
                8=>"已退款",
                9=>"拒绝退款",
                10=>"下单退款失败",
            );
            $refundArr = array(
                1=>"申请退款中",
                2=>"退款成功",
                3=>"拒绝退款",
            );
            $ExportExcel = new ExportExcel();
            foreach ($orderList as $k=>$v) {
                $data = array();
                $data['order_no'] = $v['order_no'];
                $goods_name = $ExportExcel->filterEmoji($v['goods']['goods_name']);
                $data['goods_name'] = $goods_name;
                $member_nickname = $ExportExcel->filterEmoji($v['member']['member_nickname']);
                $data['member_nickname'] = " ".$member_nickname;
                $data['fold_money'] = "¥ ".$v['fold_money'];
                $data['phone'] = " ".$v['phone'];
                $data['orderStyle'] = $styleArr[$v['order_status']];
                if($v['refund_status']>0){
                    $data['orderStyle'] = $refundArr[$v['refund_status']];
                }
                $data['creattime'] = $v['creattime'];
                $data['travelDate'] = $v['travelDate'];
                $dataArr[] = $data;
            }
            $table_head = array("订单编号","商品名","会员名","订单金额","联系电话","订单状态","下单时间","出行时间");
            $ExportExcel->exportExcel($dataArr, $table_head, "订单列表");
        }else{
            $this->assign('my_paginate',$paginate);
            $this->assign('order',$orderList);
            $this->assign('wherelist',$post);

            //获取用户信息 判断管理员登记
            $admin_id = Cookie::get("admin");
            if(isset($admin_id)){
                $cookie = Db::name('admin')->where('id',$admin_id)->find();
                $is_super_admin = $cookie['admin_cate_id']==1?true:false;
            }else{
                $is_super_admin = false;
            }
            $this->assign('issuper',$is_super_admin);
            return $this->fetch();
        }
    }


    public function Details(){
        $id=input('id');
        $source=input('source');//mongo  or  mysql
        $order_no=input('order_no');

        $orderperson=''; //出行人员信息

        if($source==1){
            $details=new Od();
            $data = $details->where('order_id',$id)->find();
            $resData = $data;
            $orderperson=$data->toArray()['orderperson'];
            $orderperson=$this->object_array(json_decode($orderperson));
        }else{
            $KbxOrder = new KbxOrder();
            $data = $KbxOrder->kbx_order_by_no($order_no);//获取订单信息
            if($data['orderType']=="CarPool"){//拼团
                $data['typeSource'] = "myself";
                $data['goods']['goodsName'] = $data['carPoolOrder']['name']??"";
                $data['goods']['goodsId'] = $data['carPoolOrder']['line']??"";
                $data['goods']['totalnum'] = 1;
                $data['payments']['originalMoney'] = $data['payments']['foldMoney'];
                $data['itinerary']['travelDate'] = $data['carPoolOrder']['details']['startDate']??"";
                $data['contact']['phone'] = $data['customer']['username']??"";
                $data['contact']['wechat'] = $data['customer']['wechat']['number']??"";
                $data['contact']['email'] = $data['customer']['email']??"";
                $data['contact']['name'] = $data['customer']['profile']['name']??"";

            }elseif($data['orderType']=="CustomMade"){//定制
                $data['typeSource'] = "myself";
                $data['goods']['goodsName'] = $data['orderName']??"";
                $data['goods']['goodsId'] = $data['tripId']??"";
                $data['goods']['totalnum'] = 1;
                $data['payments']['originalMoney'] = $data['payments']['online']['amount'];
                $data['payments']['foldMoney'] = $data['payments']['online']['amount'];
                $data['itinerary']['travelDate'] = $data['details']['startDate']??"";
                $data['contact']['phone'] = $data['consumer']['contact']['phone']??"";
                $data['contact']['wechat'] = $data['consumer']['contact']['wechat']??"";
                $data['contact']['email'] = $data['consumer']['contact']['email']??"";
                $data['contact']['name'] = $data['consumer']['contact']['name']??"";
            }else{
                $data['goods']['goodsId'] = $data['goods']['goodsId']??0;                $data['goods']['goodsId'] = $data['goods']['goodsId']??0;
                $data['payments']['foldMoney'] = $data['payments']['foldMoney']??'未知';
                $data['payments']['originalMoney'] = $data['payments']['originalMoney']??$data['payments']['foldMoney'];            }

            $order = array();
            $grade_name = isset($data['goods']['gradeName']) ? $data['goods']['gradeName'] : '';
            $order['orderType'] = $data['orderType']??"";
            $order['order_no'] = $order_no;
            $data['typeSource'] = $data['typeSource']??1;
            $show = $data['typeSource']=='myself' ? 1 : 2;
            $order['goods'] = array('goods_name'=>$data['goods']['goodsName'],'goods_id'=>$data['goods']['goodsId'],'show'=>$show);
            $order['speedstatus'] = isset($data['speedStatus']) ? $data['speedStatus'] : 0;
            $order['grade_name'] = $grade_name;
            $order['member']['member_nickname'] = isset($data['booker']['user']['profile']['name']) ? $data['booker']['user']['profile']['name'] : '';
            $order['contact_xing'] = isset($data['contact']['name']) ? $data['contact']['name'] : '';
            $order['contact_ming'] = '';
            $order['wechat_number'] = isset($data['contact']['wechat']) ? $data['contact']['wechat'] : '';
            $order['phone'] = isset($data['contact']['phone']) ? $data['contact']['phone'] : '';
            $order['e_mail'] = isset($data['contact']['email']) ? $data['contact']['email'] : '';
            $order['totalnum'] = $data['goods']['totalnum'];
            $order['travel_date'] = $data['itinerary']['travelDate'];
            $order['original_money'] = $data['payments']['originalMoney'];
            $order['fold_money'] = $data['payments']['foldMoney'];
            $order['creattime'] = strtotime($data['createdAt']);
            $order['updatetime'] = strtotime($data['updatedAt']);
            $order['serve_address'] = isset($data['contact']['serveAddress']) ? $data['contact']['serveAddress'] : '';
            $order['remarks'] = isset($data['contact']['remarks']) ? $data['contact']['remarks'] : '';
            $orderperson = isset($data['itinerary']['orderPerson'])?$data['itinerary']['orderPerson']:'';

            //判断状态
            $orderStatus = $data['status']['orderStatus'];
            $paymentStatus = $data['status']['paymentStatus'];
            $order['order_status']= 1;
            if($orderStatus=='pending'){
                if($paymentStatus=='pending'){
                    $order['order_status']= 1;//待付款
                }elseif($paymentStatus=='paid'){
                    $order['order_status']= 2;//已付款待使用
                }elseif($paymentStatus=='refunding'){
                    $order['order_status']= 5;//退款申请中
                }elseif($paymentStatus=='rejected'){
                    $order['order_status']= 9;//拒绝退款
                }
            }elseif($orderStatus=='toBeStarting'){
                if($paymentStatus=='paid'){
                    $order['order_status']= 2;//已付款待使用
                }elseif($paymentStatus=='refunding'){
                    $order['order_status']= 5;//退款申请中
                }elseif($paymentStatus=='rejected'){
                    $order['order_status']= 9;//拒绝退款
                }
            }elseif($orderStatus=='reviewed'){//已评价
                $order['order_status']= 4;
            }elseif($orderStatus=='finished'){//已使用待评价
                $order['order_status']= 3;
            }elseif($orderStatus=='canceled'){//已取消
                if($paymentStatus=='refunded'){
                    $order['order_status']= 8;//已退款
                }else{
                    $order['order_status']= 6;
                }
            }elseif($orderStatus=='expired'){//已过期
                $order['order_status']= 7;
            }elseif($orderStatus=='unknown'){//下单失败
                $order['order_status']= 10;
            }

            $resData = $order;
        }
        //产品跳转链接
        $resData['hasRef'] = false;
        $resData['refUrl'] = '';
        $resData['refTag'] = '';
        $resData['orderType'] = $resData['orderType']??"";
        if(!empty($resData['goods']['goods_id']) || !empty($resData['goods_id'])){
            $id = $resData['goods']['goods_id']??$resData['goods_id'];
            $resData['hasRef'] = true;
            if($resData['orderType']=='CustomMade'){
                $resData['refUrl'] = '/admin/quicktrip/tripmake/id/'.$id;
                $resData['refTag'] = '定制';
            }elseif($resData['orderType']=='CarPool'){
                $resData['refUrl'] = '/admin/grouptoursline/edit/id/'.$id;
                $resData['refTag'] = '拼团';
            }else{
                $goodsInfo = db('goods')->find($id);
                $resData['hasRef'] = false;
                if(!empty($goodsInfo)){//商品存在
                    $resData['hasRef'] = true;
                    if(!empty($goodsInfo['goods_tcode'])){
                        $productInfo = db('product')->where('item_num',$goodsInfo['goods_tcode'])->find();
                    }
                    //存在产品
                    if(!empty($productInfo)){
                        $id = $productInfo['id'];
                        $resData['refUrl'] = '/admin/product/productmake/id/'.$id;
                        $resData['refTag'] = '产品';
                    }else{
                        if($goodsInfo['show']==2){
                            $resData['refUrl'] = '/admin/goods/addgoodsother/id/'.$id;
                            $resData['refTag'] = 'Viator';
                        }else{
                            $resData['refUrl'] = '/admin/goods/addgoods/id/'.$id;
                            $resData['refTag'] = '自营';
                        }
                    }
                }
            }
        }
        $this->assign('dats',$resData);
        $this->assign('person',$orderperson);
        return $this->fetch();
    }

    //取消
    public function cancel(){
        $id=input('id');
        $cancel=new Od();
        if (!empty($id)){
            $da=$cancel->cancel($id);
            if ($da==true){
                $order= $cancel->where('order_id',$id)->find();
                if ($order['coupon_type']=='KBX'){
                    $Kbxcoupon= new Kbxcoupon();
                    $d= $Kbxcoupon->refundCashCoupon($order['member_id'],$order['cost_ticket_id'],$order['order_no']);
                    if (empty($d)){
                        $d=true;
                    }else{
                        $d=json_decode($d,true);
                        if (!empty($d['msg'])) return $this->error($d['msg']);
                    }
                    if ($d){
                        return $this->success('取消成功');
                    }else{
                        return $this->error('取消失败');
                    }
                }else{
                    //优惠券退回操作
                    db('coupondetails')->where('id',$order['cost_ticket_id'])->update(['usestatus'=>0]);

                }
                return $this->success('取消成功');
            }else{
                return $this->error('取消失败');
            }
        }else{
            return $this ->error('已经付款的订单不能取消');
        }
    }

    //完成订单
    public function carryout(){
        $order_id=input('id');
        if ($order_id){
            $da=db('order')->where('order_id',$order_id)->update([
                'order_status'=>3,
                'updatetime'=>time()
            ]);

            $admin = Cookie::get('admin');
            $log[]=[
                '完成订单'=>array(
                    '订单id'=>$order_id,
                    '时间'=>date("Y-m-d H:i:s",time()),
                    'admin'=>isset($admin)?$admin:'',
                ),
            ];
            Log::record($log);

            if ($da){
                $member = Db::name('order')->where(['order_id' => $order_id])->find();//查询订单
                //判断评论状态是否是已经评论过的  0 不能评论 1 可以评论 2 已评论
                if ($member['comment_type']==0){
                    $da = db('order')->where('order_id',$order_id)->update([
                        'comment_type'  => 1,
                    ]);
                }

                if (!empty($member['member_pcode'])){
                    //查询推荐用户
                    $member1=db('member')->where('member_id',$member['member_pcode'])->find();
                    //获取推荐用户的佣金率
                    $commission_per=db('member_type')->where('member_type_id',$member1['member_type_id'])->find();

                    //2018-10-30  重写
                    //by suley
                    //计算用户获得的佣金
                    $goods_id = $member['goods_id'];//商品id
                    $goods_data = Db::name('goods')->where(['goods_id' => $goods_id])->find();//查询商品分类
                    $classify_id = $goods_data['classify_id'];//商品分类id

                    $classify_info = Db::name('classify')->where("classify_status",1)->select();
                    //加入包车和接送机
                    $classify_info[] = array("classify_id"=>304,"classify_name"=>"接送机","classify_status"=>1,"creattime"=>0,"updatetime"=>0);
                    $classify_info[] = array("classify_id"=>305,"classify_name"=>"包车","classify_status"=>1,"creattime"=>0,"updatetime"=>0);
                    $classArr = array();
                    foreach ($classify_info as $v) {
                        $classArr[] = $v['classify_id'];
                    }

                    //拆分 返佣利率字符串
                    $commission_per_list = $commission_per['commission_per_list'];
                    if($commission_per_list && $commission_per_list!==''){
                        $commission_per_arr = explode(",",$commission_per_list);
                        $all_per_arr = array();
                        foreach ($commission_per_arr as $per_value){
                            $per_arr = explode("_",$per_value);
                            $per_classify_id = $per_arr[0];
                            if(!in_array($per_classify_id,$classArr)){
                                continue;
                            }
                            $per = $per_arr[1];
                            $all_per_arr[$per_classify_id] = $per;
                        }

                        if(isset($all_per_arr[$classify_id])){
                            if( $all_per_arr[$classify_id]<0 || $all_per_arr[$classify_id]>1 ){

                            }else{
                                //计算返佣
                                $money= $member['fold_money']*$all_per_arr[$classify_id];
                                //对推荐会员的用户做累加
                                db('member')->where('member_id',$member1['member_id'])->setInc('member_money', $money);
                                //写入分销明细表
                                db('distributiondetails')->insert([
                                    'member_id'=>$member1['member_id'],
                                    'money'=>$money,
                                    'consumption_money'=>$member['fold_money'],
                                    'consumption_time'=>$member['creattime'],
                                    'consumption_goods'=>$member['goods_id'],
                                    'consumption_member_id'=>$member['member_id'],
                                    'consumption_order_id'=>$order_id,
                                ]);
                            }
                        }
                    }

                    $log[]=[
                        '计算佣金数据'=>array(
                            '推荐人会员等级'=>$member1['member_type_id'],
                            '商品分类id'=>$classify_id,
                            '利率str'=>$commission_per_list
                        ),
                    ];
                    Log::record($log);
                }

                Db::name('member')->where(['member_id' => $member['member_id']])->setInc('member_integral', $member['add_integral']);//增加用户积分
                Db::name('member_integrallog')->insert([//写入积分日志
                    'member_id'=> $member['member_id'],
                    'describe'=>'消费所得',
                    'integral'=>$member['add_integral'],
                    'create_time'=>time()
                ]);
                $membertr= db('member')->where('member_id',$member['member_id'])->find();
                $Notify= new Notify();
                $content="
               <p><b>尊敬的 ".$membertr['member_nickname']." ，您好：</b></p>
    <p>&nbsp;&nbsp;&nbsp;&nbsp;感谢您选择快帮行服务，一段旅程的结束是另一段新旅程的开始，写下您的出行感受，
     分享您的好心情， 在快帮行公众号（kwibon）点击底部菜单“发现”-“我的”进入个人中心，为您的出行订单完成好评，还可获取 <span style='color:#ff7d00 '> 20 </span> 积分，累计积分带给你新的惊喜。</p>
    
<div style='opacity:1;position: relative;'>
    <p>&nbsp;&nbsp;&nbsp;&nbsp;* 国内客服: <a>+86 400-100-5295</a></p>
    <p>&nbsp;&nbsp;&nbsp;&nbsp;* 北美客服: <a>+1 800-932-1178</a></p>
    <p>&nbsp;&nbsp;&nbsp;&nbsp;* 客服微信：<a>kbxmei</a></p>
    <p>&nbsp;&nbsp;&nbsp;&nbsp;  官网：<a href='http://www.kuaibangxing.com'>http://www.kuaibangxing.com</a></p>
         <div style=' position: absolute ;background: url(https://c.kuaibangxing.com/uploads/admin/admin_thumb/20181011/f559459c585157808d9c95ee040b03cc.png) no-repeat 5% 5% ;width: 50%;bottom:-9px;height: 150px;
opacity:0.08; background-size: 300px; '>  </div> 
            
            </div>   ";

                $subject='行程完成通知';
                $address=$member['e_mail'];
                $Notify->kbxemailcode($subject,$content,$address);
                $shu=[
                    'msg'=>'修改成功',
                    'code'=>1
                ];
                return $shu;
            }else{
                $shu=[
                    'msg'=>'修改失败',
                    'code'=>101
                ];
                return $shu;
            }
        }
    }


    public function refuse(){
        $m = new Od;
        $order_id= input('order_id');
        $order_no = input('order_no');
        $source = input('source');// 1为mysql  2为mongo
        $KbxOrder = new KbxOrder();
        if (request()->post()) {
            if ($source == 1) {//mysql
                $order= $m->where('order_id',$order_id)->Update([
                    'refund_status'=>3,
                    'order_status'=>9,
                    'updatetime'=>time()
                ]);
                if ($order==true){
                    return $this->success('已成功拒绝退款');
                }else{
                    $shu=[
                        'msg'=>'操作失败请重试',
                        'code'=>101
                    ];
                    return json_decode($shu);
                }
            } else {//mongo
                $order = $KbxOrder->kbx_order_by_no($order_no);//获取订单信息
                $postUpdateArr = [
                    'id'=>$order_id,
                    'statusPhp'=>array(
                        'orderStatus'=>9,
                    ),
                    'status'=>array(
                        'orderStatus'=>$this->statusArr[9]['orderStatus'],
                        'paymentStatus'=>$this->statusArr[9]['paymentStatus'],
                    ),
                    'refund'=>array(
                        'refundStatus'=>3,
                    ),
                ];
                $update_res = $KbxOrder->kbx_operate_order($order['orderType'],$postUpdateArr);
                $log[]=[
                    '自由平台后台：后台退款-拒绝退款'=>json_encode($postUpdateArr),
                    'res'=>$update_res
                ];
                Log::record($log);

                if ($update_res){
                    return $this->success('已成功拒绝退款');
                }else{
                    $shu=[
                        'msg'=>'操作失败请重试',
                        'code'=>101
                    ];
                    return json_decode($shu);
                }
            }
        }else{
            return $this->success('操作失败');
        }


    }


    public function refund(){//微信退款操作
        $m = new Od;
        $order_id = input('order_id');
        $order_no = input('order_no');
        $source = input('source');// 1为mysql  2为mongo
        $KbxOrder = new KbxOrder();
        if (request()->post()){
            $refund_money = input('refund_money');//退款金额
            if($source==1){//mysql
                $order = $m->where('order_id',$order_id)->find();


                //此处验证使退款和订单取消逻辑解绑   原因：有客户过了出行日期并未出行也未取消，需要执行退款
                if (!in_array($order['order_status'],array(2,6))){
                    return $this->error('该订单不能退款');
                }else{
                    if($order['pay_type']==2){//信用卡支付
                        $credit_charge = model('Accounts')->where('order_no',$order['order_no'])->find();
                        $Notify= new Notify();
                        $refund_res = $Notify->kbxCreditRefund($credit_charge['credit_charge_id'],"后台退款");

                        $log[]=[
                            '自由平台后台：后台退款mysql-信用卡'=>json_encode($refund_res),
                            'order_no'=>$order_no
                        ];
                        Log::record($log);

                        if ($refund_res['status']==='succeeded'){//退款成功
                            //优惠券退回
                            if ($order['coupon_type']=='KBX'){
                                $Kbxcoupon= new Kbxcoupon();
                                $d= $Kbxcoupon->refundCashCoupon($order['member_id'],$order['cost_ticket_id'],$order['order_no']);
                                $log[]=[
                                    '自由平台后台：后台退款mysql-credit优惠券退回'=>json_encode($d),
                                    'order_no'=>$order_no
                                ];
                                Log::record($log);
                            }

                            $order1= $m->where('order_id',$order_id)->Update([
                                'refund_status'=>'2',
                                'order_status'=>'8',
                                'refund_money'=>$credit_charge['accounts_money']
                            ]);
                            if($order1){
                                $md=model('Accounts')->insert([
                                    'member_id'=>$order['member_id'],
                                    'order_no'=>$order['order_no'],
                                    'admin_id'=>Cookie::get('admin'),
                                    'accounts_money'=>$credit_charge['accounts_money'],
                                    'business_way'=>4,
                                    'description'=>"后台退款",
                                    'credit_charge_id' => $credit_charge['credit_charge_id'],//支付id
                                    'credit_charge_data' => json_encode($refund_res,true),//返回的退款data
                                    'creattime'=>date('YmdHis',time())
                                ]);
                                return $this->success('退款成功');
                            }
                        }else{//退款失败
                            return $this->error($refund_res['msg']);
                        }
                    }else{//pay_type==1 微信支付
                        if ($refund_money>0) {
                            //查询订单记录的支付流水号
                            $accountLog = db('accounts')->where('order_no',$order_no)->find();
                            if(empty($accountLog)) return $this->success('退款失败，未查询到该支付记录');
                            $out_trade_no = empty($accountLog['pay_order_no'])?$order_no.'KBX1230967564':$accountLog['pay_order_no'];
                            $aa = $this->WxRefund($out_trade_no, $order['fold_money'], $refund_money);

                            $log[]=[
                                '自由平台后台：后台退款mysql-微信支付'=>$aa,
                                'order_no'=>$order_no
                            ];
                            Log::record($log);

                            if ($aa === true) {
                                //优惠券退回
                                if ($order['coupon_type']=='KBX'){
                                    $Kbxcoupon= new Kbxcoupon();
                                    $d= $Kbxcoupon->refundCashCoupon($order['member_id'],$order['cost_ticket_id'],$order['order_no']);
                                    $log[]=[
                                        '自由平台后台：后台退款mysql-wx优惠券退回'=>$d,
                                        'order_no'=>$order_no
                                    ];
                                    Log::record($log);
                                }

                                $order1 = $m->where('order_id', $order_id)->Update([
                                    'refund_status' => '2',
                                    'order_status' => '8',
                                    'refund_money' => $refund_money
                                ]);
                                if ($order1) {
                                    $md = model('Accounts')->insert([
                                        'member_id' => $order['member_id'],
                                        'admin_id' => Cookie::get('admin'),
                                        'accounts_money' => $refund_money,
                                        'business_way' => 4,
                                        'creattime' => date('YmdHis', time())
                                    ]);
                                    return $this->success('退款成功');
                                }
                            } else {
                                return $this->error("$aa");
                            }
                        }else{
                            //优惠券退回
                            if ($order['coupon_type']=='KBX') {
                                $Kbxcoupon = new Kbxcoupon();
                                $d = $Kbxcoupon->refundCashCoupon($order['member_id'], $order['cost_ticket_id'], $order['order_no']);
                                $log[] = [
                                    '自由平台后台：后台退款mysql-单纯优惠券退回' => $d,
                                    'order_no' => $order_no
                                ];
                                Log::record($log);

                                $order1 = $m->where('order_id', $order_id)->Update([
                                    'refund_status' => '2',
                                    'order_status' => '8',
                                    'refund_money' => $refund_money
                                ]);
                                if ($order1) {
                                    $md = model('Accounts')->insert([
                                        'member_id' => $order['member_id'],
                                        'admin_id' => Cookie::get('admin'),
                                        'accounts_money' => $refund_money,
                                        'business_way' => 4,
                                        'creattime' => date('YmdHis', time())
                                    ]);
                                    return $this->success('退款成功');
                                }else{
                                    return $this->success('退款失败');
                                }
                            }
                        }
                    }
                }
            }else{//mongo
                $order = $KbxOrder->kbx_order_by_no($order_no);//获取订单信息
                if ($order['status']['paymentStatus']!=='paid'){
                    return $this->error('该订单不能退款');
                }else{
                    $payType = isset($order['payType'])?$order['payType']:1;
                    if($payType==2){//信用卡支付
                        $credit_charge = model('Accounts')->where('order_no',$order_no)->find();
                        $Notify= new Notify();
                        $refund_res = $Notify->kbxCreditRefund($credit_charge['credit_charge_id'],"后台退款");
                        if ($refund_res['status']==='succeeded'){//退款成功
                            //优惠券退回
                            if ($order['payments']['couponType']=='KBX'){
                                $Kbxcoupon= new Kbxcoupon();
                                $d= $Kbxcoupon->refundCashCoupon($order['booker']['memberId'],$order['payments']['costTicketId'],$order_no);
                                $log[]=[
                                    '自由平台后台：后台退款mongo-credit优惠券退回'=>$d,
                                    'order_no'=>$order_no
                                ];
                                Log::record($log);
                            }
                            //退款成功
                            $postUpdateArr = [
                                'id'=>$order_id,
                                'statusPhp'=>array(
                                    'orderStatus'=>8,
                                ),
                                'status'=>array(
                                    'orderStatus'=>$this->statusArr[8]['orderStatus'],
                                    'paymentStatus'=>$this->statusArr[8]['paymentStatus'],
                                ),
                                'refund'=>array(
                                    'refundMoney'=>$order['payments']['foldMoney'],
                                    'refundStatus'=>2,
                                ),
                            ];
                            $update_res = $KbxOrder->kbx_operate_order($order['orderType'],$postUpdateArr,true);
                            $log[]=[
                                '自由平台后台：后台退款-信用卡退款成功'=>json_encode($postUpdateArr),
                                'res'=>$update_res
                            ];
                            Log::record($log);

                            if($update_res){
                                $md=model('Accounts')->insert([
                                    'member_id'=>$order['booker']['memberId'],
                                    'order_no'=>$order_no,
                                    'admin_id'=>Cookie::get('admin'),
                                    'accounts_money'=>$credit_charge['accounts_money'],
                                    'business_way'=>4,
                                    'description'=>"后台退款",
                                    'credit_charge_id' => $credit_charge['credit_charge_id'],//支付id
                                    'credit_charge_data' => json_encode($refund_res,true),//返回的退款data
                                    'creattime'=>date('YmdHis',time())
                                ]);
                                return $this->success('退款成功');
                            }
                        }else{//退款失败
                            return $this->error($refund_res['msg']);
                        }
                    }else{//pay_type==1 微信支付
                        if ($refund_money>0) {
                            //查询订单记录的支付流水号
                            $accountLog = db('accounts')->where('order_no',$order_no)->find();
                            if(empty($accountLog)) return $this->success('退款失败，未查询到该支付记录');
                            $out_trade_no = empty($accountLog['pay_order_no'])?$order_no.'KBX1230967564':$accountLog['pay_order_no'];
                            $aa= $this->WxRefund($out_trade_no,$order['payments']['foldMoney'],$refund_money);
                            if ($aa===true){
                                //优惠券退回
                                if ($order['payments']['couponType']=='KBX'){
                                    $Kbxcoupon= new Kbxcoupon();
                                    $d= $Kbxcoupon->refundCashCoupon($order['booker']['memberId'],$order['payments']['costTicketId'],$order_no);
                                    $log[]=[
                                        '自由平台后台：后台退款mongo-wx优惠券退回'=>$d,
                                        'order_no'=>$order_no
                                    ];
                                    Log::record($log);
                                }
                                //退款成功
                                $postUpdateArr = [
                                    'id'=>$order_id,
                                    'statusPhp'=>array(
                                        'orderStatus'=>8,
                                    ),
                                    'status'=>array(
                                        'orderStatus'=>$this->statusArr[8]['orderStatus'],
                                        'paymentStatus'=>$this->statusArr[8]['paymentStatus'],
                                    ),
                                    'refund'=>array(
                                        'refundMoney'=>$order['payments']['foldMoney'],
                                        'refundStatus'=>2,
                                    ),
                                ];
                                $update_res = $KbxOrder->kbx_operate_order($order['orderType'],$postUpdateArr);
                                $log[]=[
                                    '自由平台后台：后台退款-微信退款成功'=>json_encode($postUpdateArr),
                                    'res'=>$update_res
                                ];
                                Log::record($log);

                                if($update_res){
                                    $md = model('Accounts')->insert([
                                        'member_id'=>$order['booker']['memberId'],
                                        'admin_id'=>Cookie::get('admin'),
                                        'accounts_money'=>$refund_money,
                                        'business_way'=>4,
                                        'creattime'=>date('YmdHis',time())
                                    ]);
                                    return $this->success('退款成功');
                                }
                            }else{
                                return $this->error("$aa");
                            }
                        }else{
                            //优惠券退回
                            if ($order['payments']['couponType']=='KBX'){
                                $Kbxcoupon= new Kbxcoupon();
                                $d= $Kbxcoupon->refundCashCoupon($order['booker']['memberId'],$order['payments']['costTicketId'],$order_no);

                                //退款成功
                                $postUpdateArr = [
                                    'id'=>$order_id,
                                    'statusPhp'=>array(
                                        'orderStatus'=>8,
                                    ),
                                    'status'=>array(
                                        'orderStatus'=>$this->statusArr[8]['orderStatus'],
                                        'paymentStatus'=>$this->statusArr[8]['paymentStatus'],
                                    ),
                                    'refund'=>array(
                                        'refundMoney'=>$order['payments']['foldMoney'],
                                        'refundStatus'=>2,
                                    ),
                                ];
                                $update_res = $KbxOrder->kbx_operate_order($order['orderType'],$postUpdateArr);
                                $log[]=[
                                    '自由平台后台：后台退款-单纯优惠券退回'=>json_encode($postUpdateArr),
                                    'res'=>$update_res
                                ];
                                Log::record($log);

                                if($update_res){
                                    $md=model('Accounts')->insert([
                                        'member_id'=>$order['booker']['memberId'],
                                        'admin_id'=>Cookie::get('admin'),
                                        'accounts_money'=>$refund_money,
                                        'business_way'=>4,
                                        'creattime'=>date('YmdHis',time())
                                    ]);
                                    return $this->success('退款成功');
                                }else{
                                    return $this->success('退款失败');
                                }
                            }
                        }
                    }
                }
            }
        }else{//展示金额
            if($source==1) {//mysql
                $order = $m->where('order_id',$order_id)->find();
                $order['source'] = $source;
                $payType = isset($order['pay_type'])?$order['pay_type']:1;
                $order['payType'] = $payType;
                $order['business_way'] = $payType==1 ? "微信" : "信用卡";
            }else{//mongo
                $KbxOrder = new KbxOrder();
                $data = $KbxOrder->kbx_order_by_no($order_no);//获取订单信息
                $order['source'] = $source;
                $order['order_no'] = $order_no;
                $order['order_id'] = $order_id;
                $payType = isset($data['payType'])?$data['payType']:1;
                $order['payType'] = $payType;
                $order['business_way'] = $payType==1 ? "微信" : "信用卡";
                $order['fold_money'] = isset($data['payments']['foldMoney']) ? $data['payments']['foldMoney'] : 0;
            }
        }

        $this->assign('dat',$order);
        return  $this->fetch();
    }


    /*
     * @ out_trade_no 商户订单号
     * @ total_fee 订单总金额 单位为分
     * @ refund_fee 退款金额
     */
    public function WxRefund($out_trade_no,$total_fee,$refund_fee){
//    Loader::import('WeiXinpay.lib.WxPay', EXTEND_PATH, '.Api.php');
        vendor('WeiXinpay.wxpay');
        if($out_trade_no) {
            $input = new \WxPayRefund();

            $input->SetOut_trade_no($out_trade_no);
            $input->SetTotal_fee($total_fee * 100);
            $input->SetRefund_fee($refund_fee * 100);
            $input->SetOut_refund_no(\WxPayConfig::MCHID . date("YmdHis"));
            $input->SetOp_user_id(\WxPayConfig::MCHID);
//        $input->SetNotify_url('https://api.mch.weixin.qq.com/secapi/pay/refund');
//        $input->SetNotify_url('http://kbx.combadc.com/admin/order/refund');
//        https://api.mch.weixin.qq.com/secapi/pay/refund
//        var_dump($input);die();
            $result = \WxPayApi::refund($input);

            if (($result['return_code'] == 'SUCCESS') && ($result['result_code'] == 'SUCCESS')) {
                //退款成功
                $reason = true;
            } else if (($result['return_code'] == 'FAIL') || ($result['result_code'] == 'FAIL')) {
                //退款失败
                //原因
                $reason ='退款失败--'. (empty($result['err_code_des']) ? $result['return_msg'] : $result['err_code_des']);
            } else {
                //失败
                $reason = '退款失败';
            }



            return $reason;
        }

    }


    //撤销订单
    public function calOrder(){
        if($this->request->isPost()){
            $id=input('order_id');
            $code=input('code');
            $msg=input('msg');

            $data=Db::name('order')->where('order_id',$id)->find();
            if($data['order_status']!=2){
                $arr=['code'=>'001','msg'=>'订单只有在已支付且未出行的状态下，才可以撤销'];
                return $arr;
            }
            if(empty($data['viatorid'])){
                $arr=['code'=>'002','msg'=>'参数异常，请核对该订单是否正常下单'];
                return $arr;
            }
            $data_res=Db::name('order_byviator')->where('id',$data['viatorid'])->find();
            //撤销
            $itineraryId=$data_res['itineraryId'];
            $distributorRef=$data_res['distributorRef'];
            $itemId=$data_res['itemId'];
            $distributorItemRef=$data_res['distributorItemRef'];

            $list=[
                'itineraryId'=>$itineraryId,
                'distributorRef'=>$distributorRef,
                'cancelItems'=>[
                    [
                        'itemId'=>$itemId,
                        'distributorItemRef'=>$distributorItemRef,
                        'cancelCode'=>$code,
                    ]
                ],
            ];
            if($code==62 || $code==66){
                $list['cancelItems'][0]['cancelDescription']=$msg;
            }
            $viator=new Viator();
            $res=$viator->cancelBooking($list);
            $res=$viator->object_array($res);
            $status=$res['data']['cancelItems'][0]['cancellationResponseStatusCode'];
            switch ($status){
                case 'Confirmed':
                    $arr=['code'=>'003','msg'=>'撤销订单的请求已经被接受和处理'];
                    break;
                case 'Pending':
                    $arr=['code'=>'004','msg'=>'撤销订单已申请'];
                    break;
                case 'Rejected':
                    $arr=['code'=>'005','msg'=>'申请被拒绝'];
                    break;
                case 'Available':
                    $arr=['code'=>'006','msg'=>'项目可以取消'];
                    break;
                default:
                    $arr=['code'=>'002','msg'=>'撤销订单失败'];
                    break;
            }
            return $arr;
        }else{
            $id=input('id');
            $dat=Db::name('order')->where('order_id',$id)->find();
            $this->assign('dat',$dat);
            return $this->fetch();
        }

    }




    //新 底部分页返回  By Suley
    public function myPaginate($page,$totalPages,$totalNum,$url)
    {
        $prevpage = $page-1;
        $prevpage = $prevpage>0 ? $prevpage : 1;//上一页
        $nextpage = $page+1;
        $nextpage = $nextpage>$totalPages ? $totalPages : $nextpage;//下一页

        $paginate = '<div class="pagination">';
        $paginate .= '<a href="'.$url.'?page=1" title="首页">首页</a>';
        $paginate .= '<a href="'.$url.'?page='.$prevpage.'" title="上一页">上一页</a>';

        if($totalPages<=10){
            for ($i=1;$i<=$totalPages;$i++){
                if($i==$page){
                    $paginate .= '<a href="" class="cur">'.$i.'</a>';
                }else{
                    $paginate .= '<a href="'.$url.'?page='.$i.'" title="第" '.$i.'"页"="">'.$i.'</a>';
                }
            }
        }else{
            if($page<=3){
                for ($i=1;$i<=8;$i++){
                    if($i==$page){
                        $paginate .= '<a href="" class="cur">'.$page.'</a>';
                    }else{
                        $paginate .= '<a href="'.$url.'?page='.$i.'" title="第 '.$i.'页">'.$i.'</a>';
                    }
                }
                $lastSecondPage = $totalPages-1;
                $paginate .= '<p class="pageEllipsis">...</p>';
                $paginate .= '<a href="'.$url.'?page='.$lastSecondPage.'" title="第'.$lastSecondPage.'页">'.$lastSecondPage.'</a>';
                $paginate .= '<a href="'.$url.'?page='.$totalPages.'" title="第'.$totalPages.'页">'.$totalPages.'</a>';
            }elseif($page>=($totalPages-3)){
                $paginate .= '<a href="'.$url.'?page=1" title="第1页">1</a>';
                $paginate .= '<a href="'.$url.'?page=2" title="第2页">2</a>';
                $paginate .= '<p class="pageEllipsis">...</p>';
                for ($i=($totalPages-8);$i<=$totalPages;$i++){
                    if($i==$page){
                        $paginate .= '<a href="" class="cur">'.$page.'</a>';
                    }else{
                        $paginate .= '<a href="'.$url.'?page='.$i.'" title="第'.$i.'页">'.$i.'</a>';
                    }
                }
            }else{
                $paginate .= '<a href="'.$url.'?page=1" title="第1页">1</a>';
                $paginate .= '<a href="'.$url.'?page=2" title="第2页">2</a>';
                $paginate .= '<p class="pageEllipsis">...</p>';
                $page_s = $page-3;
                $page_e = $page+3;
                for ($i=$page_s;$i<=$page_e;$i++){
                    if($i==$page){
                        $paginate .= '<a href="" class="cur">'.$i.'</a>';
                    }else{
                        $paginate .= '<a href="'.$url.'?page='.$i.'" title="第'.$i.'页">'.$i.'</a>';
                    }
                }
                $lastSecondPage = $totalPages-1;
                $paginate .= '<p class="pageEllipsis">...</p>';
                $paginate .= '<a href="'.$url.'?page='.$lastSecondPage.'" title="第'.$lastSecondPage.'页">'.$lastSecondPage.'</a>';
                $paginate .= '<a href="'.$url.'?page='.$totalPages.'" title="第'.$totalPages.'页">'.$totalPages.'</a>';
            }
        }

        $paginate .= '<a href="'.$url.'?page='.$nextpage.'" title="下一页">下一页</a>';
        $paginate .= '<a href="'.$url.'?page='.$totalPages.'" title="尾页">尾页</a>';
        $paginate .= '<p class="pageRemark">共<b>'.$totalPages.'</b>页<b>'.$totalNum.'</b>条数据</p></div>';

        return $paginate;
    }



    //针对自营二次确认
    public function confirmStatus(){
        $id=input('id');
        $res = Db::name('order')->where(['order_id'=>$id])->update(['speedstatus'=>2]);

        if ($res){
            $order = Db::name('order')
                ->alias('o')
                ->join('goods g','o.goods_id=g.goods_id',"left")
                ->where(['o.order_id'=>$id])
                ->field("o.*,g.goods_name as name,g.city_id")
                ->find();
            $member = Db::name('member')->where(['member_id'=>$order['member_id']])->find();
            $city = Db::name('city')->where(['id'=>$order['city_id']])->field("name")->find();

            $content= "
        <p><b>尊敬的 ".$member['member_nickname']." ，您好：</b></p>
        <p>&nbsp;&nbsp;&nbsp;&nbsp;您的订单已预订成功，祝您出行愉快，快帮行与您一路同行。</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;产品：".$city['name'] ."下的".$order['name']."</p>

<p>&nbsp;&nbsp;&nbsp;&nbsp;订单号：".$order['order_no'] ."</p>

<p>&nbsp;&nbsp;&nbsp;&nbsp;使用日期：".date('Y-m-d',strtotime($order['travel_date'])) ."</p>
 
<p>&nbsp;&nbsp;&nbsp;&nbsp;您可以在快帮行公众号（kwibon）点击底部菜单“发现”-“我的”进入个人中心 查看最新订单状态，本订单完成之后您将获取   <a href=''style='color:#ff7d00 '> ".(int)$order['add_integral']."</a>积分，预祝您的行程愉快！</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;有任何问题，请联系我们</p> 

<div style='opacity:1;position: relative;'>
    <p>&nbsp;&nbsp;&nbsp;&nbsp;* 国内客服: <a>+86 400-100-5295</a></p>
    <p>&nbsp;&nbsp;&nbsp;&nbsp;* 北美客服: <a>+1 800-932-1178</a></p>
    <p>&nbsp;&nbsp;&nbsp;&nbsp;* 客服微信：</p>
    <p style='text-align: center;'><img src='https://c.kuaibangxing.com/uploads/admin/admin_thumb/20180104/xiaomeicode1.jpg'></p>
    <p>&nbsp;&nbsp;&nbsp;&nbsp;  官网：<a href='http://www.kuaibangxing.com'>http://www.kuaibangxing.com</a></p>
    <p> <img src='https://c.kuaibangxing.com/uploads/admin/admin_thumb/20180104/kbx_adv1.jpg'> </p>
         <div style=' position: absolute ;background: url(https://c.kuaibangxing.com/uploads/admin/admin_thumb/20181011/f559459c585157808d9c95ee040b03cc.png) no-repeat 5% 5% ;width: 50%;bottom:-9px;height: 150px;
opacity:0.08; background-size: 300px; '>  </div> 
            
            </div>
        ";

            $subject='【快帮行订单】确认通知';
            $address=isset($order['e_mail']) ? $order['e_mail'] : config('SUPPORT_NOTICE_EMAIL');
            $msg=new Notify();
            //邮箱
            $msg->kbxemailcode($subject,$content,$address);

            return '已确认';
        }else{
            return '确认失败';
        }

    }

    function object_array($array) {
        if(is_object($array)) {
            $array = (array)$array;
        } if(is_array($array)) {
            foreach($array as $key=>$value) {
                $array[$key] = $this->object_array($value);
            }
        }
        return $array;
    }

}


